﻿// Copyright (c) Microsoft Corporation.  All rights reserved.

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;

// add the post model
using MyTravelPostModel;
using System.Data.Objects;
using System.Collections.Generic;

namespace ObjectServices_ASPNET_CS
{
    public partial class NewBlogPost : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                return;
            }   // if post back.

            int personID = 0;
            int.TryParse(Request.Params["PersonID"], out personID);

            // create a MyTravelEntities
            using (MyTravelEntities travelEntities = new MyTravelEntities())
            {
                // get the person and attach the person to view state for later use
                Person blogowner = travelEntities.People.First(p => p.PersonID == personID);

                // if the blogowner existed.
                if (null != blogowner)
                {
                    ViewState["Person"] = blogowner;

                    // get all the blogs, save the blogs in view state.
                    blogowner.Blogs.Load();
                    ViewState["Blogs"] = blogowner.Blogs.ToList();

                    // get the series title.
                    dropDownBlogSeries.DataTextField = "SeriesTitle";
                    dropDownBlogSeries.DataSource = blogowner.Blogs;
                    dropDownBlogSeries.DataBind();
                }
            }

            calendarDateVisited.SelectedDate = DateTime.Now;
        }

        protected void buttonSavePost_Click(object sender, EventArgs e)
        {
            // create a new blog post to the blog series selected.
            using (MyTravelEntities travelEntities = new MyTravelEntities())
            {
                // get the blog out of view state, and get the list of items.
                // select the index and attach to the travel entities.
                List<Blog> blogList = (List<Blog>)ViewState["Blogs"];
                Blog seriesBlog = null;
                string newBlogName = textNewBlog.Text;
                Person blogAuthor = (Person)ViewState["Person"];

                // if the blog name is empty, get the currently selected blog.
                if (0 == newBlogName.Length)
                {
                    seriesBlog = blogList[dropDownBlogSeries.SelectedIndex];
                    if (seriesBlog == null)
                    {
                        // probably should put an error here if this wasn't an example.
                        return;
                    }   // if

                    // attach the series blog and the person.
                    travelEntities.Attach(seriesBlog);
                }   // if
                else
                {
                    // attach the person and the blog plost.
                    travelEntities.Attach(blogAuthor);

                    // create a new blog and add to the travel entities.
                    seriesBlog = new Blog();
                    seriesBlog.SeriesTitle = newBlogName;
                    
                    // set this to the blog author
                    blogAuthor.Blogs.Add(seriesBlog);
                }   // else
                                

                // create a new blog post.
                BlogPost newPost = new BlogPost();                
                newPost.BlogDate = DateTime.Now;
                newPost.BlogTitle = textPostTitle.Text;
                newPost.CityVisited = textCity.Text;
                newPost.CountryVisited = textCountry.Text;
                newPost.DateVisited = calendarDateVisited.SelectedDate;
                newPost.BlogEntry = textBlogPost.Text;

                // add to the blog series. This adds to the objectstatemanager
                // for tracking.
                seriesBlog.BlogPosts.Add(newPost);

                try
                {
                    travelEntities.SaveChanges();
                }
                catch (OptimisticConcurrencyException opt)
                {
                    // catching this exception allows you to 
                    // refresh entities with either store/client wins
                    // project the entities into this failed entities.
                    var failedEntities = from e1 in opt.StateEntries.ToList()
                                         select new { e1.Entity };

                    // Note: in future you should be able to just pass the opt.StateEntities in to refresh.
                    travelEntities.Refresh(RefreshMode.ClientWins, failedEntities.ToList());
                    travelEntities.SaveChanges();
                }

                // clear out and then go to the travelpage.
                Response.Redirect("TravelPage.aspx?BlogID=" + seriesBlog.BlogID);
            }
        }
    }
}
